﻿#include "MainWindow.h"
#include "ui_MainWindow.h"
#include <QListWidgetItem>
#include <QFileDialog>
#include <QMessageBox>
#include <QDesktopWidget>
#include <iostream>
#include <string>
#include <regex>
#include <QToolButton>
#include <QScreen>
#include "common.h"
#include "ThreadCacheBook.h"
#include "version.h"

using namespace std;

MainWindow::MainWindow(QWidget* parent)
	: QMainWindow(parent)
	, ui(new Ui::MainWindow)
	, m_dlgAutoAddBook(this)
	, m_dlgBookCity(this)
	, m_dlgSet(this)
	, m_dlgBookRead(this)
#if WEB_WIDGET_ENABLE
	, m_webWidget(this)
#endif
{
	ui->setupUi(this);
	//设置初始化
	setGlobalFont();
	//去掉窗口的标题栏
	setWindowFlags(Qt::FramelessWindowHint);
	ui->listWidgetBook->clear();
	ReadBookListInfo();
	return;
}

MainWindow::~MainWindow()
{
	updateListWidgetBook();
	//SaveBookListInfo();
	delete ui;
}

void MainWindow::on_listWidgetBook_itemClicked(QListWidgetItem*)
{
	auto FindChapter = [&]()
		{
			if (!m_listBookInfo[0].strChapterHead.isEmpty())
				for (int id = 0; id < m_dlgBookRead.m_chapterList.size(); id++)
				{
					if (m_dlgBookRead.m_chapterList[id].head == m_listBookInfo[0].strChapterHead)
					{
						m_listBookInfo[0].chapter = id;
						break;
					}
				}
		};
	int row = ui->listWidgetBook->currentRow();//当前行
	if (!m_bDeleteBook)
	{
		if (row != 0)
		{
			g_mtxListBookPosChange.lock();
			QListWidgetItem* aItem = ui->listWidgetBook->takeItem(row); //移除指定行的项，但不delete
			ui->listWidgetBook->insertItem(0, aItem);
			m_listBookInfo.insert(m_listBookInfo.begin(), m_listBookInfo[row]);
			m_listBookInfo.erase(m_listBookInfo.begin() + row + 1);
			g_mtxListBookPosChange.unlock();
			SaveBookListInfo();
		}

		if (m_listBookInfo[0].IsWeb())//网书
		{
		GET_WEB_INFO:
			int iRet = ThreadCacheBook::GetChapterList(m_listBookInfo[0], m_dlgBookRead.m_chapterList);
			if (iRet >= 0 && m_dlgBookRead.m_chapterList.size() > 0)
			{
				FindChapter();
				m_dlgBookRead.UpdateChapter();
				m_dlgBookRead.show();
			}
			else
			{
				QMessageBox::StandardButton btnSelect;
				btnSelect = QMessageBox::warning(this, tr("警告"), m_listBookInfo[0].name + "\n" + m_listBookInfo[0].path
					+ tr("\n获取章节列表失败!是否重试?"), QMessageBox::Yes | QMessageBox::No);
				if (btnSelect == QMessageBox::Yes)
				{
					goto GET_WEB_INFO;
				}
				else
				{
					return;
				}
			}
		}
		else
		{
			int iRet = m_dlgBookRead.ParseFile();
			if (iRet < 0)
			{
				DelBook(0);
				m_dlgBookRead.hide();
			}
			else if (iRet > 0)
				return;
			else
			{
				FindChapter();
				m_dlgBookRead.UpdateChapter();
				m_dlgBookRead.show();
			}
		}
	}
	else
	{
		DelBook(row);
	}
}

void MainWindow::on_btnAddBook_clicked()
{
	QIcon aIcon;
	aIcon.addFile(QStringLiteral(":/assets/images/image_book.jpg")); //设置ICON的图标

	//选择多个文件
	//获取应用程序的路径
	QString curPath = QDir::currentPath();//获取系统当前目录
#ifdef __ANDROID__
	curPath = ROOT_PATH;
#endif
	QString dlgTitle = "选择多个文件"; //对话框标题
	QString filter = "文本文件(*.*)";//"文本文件(*.txt);图片文件(*.jpg *.gif *.png);所有文件(*.*)"; //文件过滤器
	QFileDialog fd(this, dlgTitle, curPath, filter);
	fd.setGeometry(geometry());
	fd.setNameFilter("文本文件(*.*)");
	fd.setViewMode(QFileDialog::Detail); //设置浏览模式，有 列表（list） 模式和 详细信息（detail）两种方式
	fd.setFileMode(QFileDialog::ExistingFiles);
	fd.setAcceptMode(QFileDialog::AcceptOpen);
	fd.setOption(QFileDialog::ReadOnly);
	QStringList fileList;
	if (fd.exec() == QDialog::Accepted)   //如果成功的执行
	{
		fileList = fd.selectedFiles();      //返回文件列表的名称
	}
	else
		fd.close();

	int i = 0;
	for (; i < fileList.count(); i++)
	{
		QString strPath = fileList.at(i);
		QFileInfo  info = QFileInfo(fileList.at(i));
		QString strBookFileName = info.fileName();
		AddBookInfoToWeiget(sBookInfo(strBookFileName, strPath), 0);
	}
	SaveBookListInfo();
}

void MainWindow::on_btnDeleteBook_clicked()
{
	if (m_bDeleteBook)
	{
		m_bDeleteBook = 0;
		ui->btnDeleteBook->setText(tr("删书"));

		//背景样式恢复
		QPalette pOne = ui->btnAddBook->palette();
		ui->btnDeleteBook->setPalette(pOne);
	}
	else
	{
		m_bDeleteBook = 1;
		ui->btnDeleteBook->setText(ui->btnDeleteBook->text() + BUTTON_IN_PROGRESS);
		QPalette pOne = ui->btnDeleteBook->palette();
		pOne.setColor(QPalette::ButtonText, Qt::red);
		ui->btnDeleteBook->setPalette(pOne);
	}
}

void MainWindow::AddBookInfoToWeiget(sBookInfo book, int indexItem)
{
	for (auto& book_info : m_listBookInfo)
	{
		if (book.path.size() == book_info.path.size() && book.path == book_info.path)
		{
			return;
		}
	}

	book.ReadChapterInfo();

	QIcon aIcon;
	aIcon.addFile(QStringLiteral(":/assets/images/image_book.jpg")); //设置ICON的图标
	QIcon aIconNet;
	QString strFilePathImage = BOOK_LIST_SAVE_DIR"cache/" + book.name + WEB_BOOK_IMAGE_FILE_NAME;
	struct stat buffer;
	if (stat(strFilePathImage.toLocal8Bit(), &buffer) == 0)
	{
		aIconNet.addFile(strFilePathImage);
	}
	else
		aIconNet.addFile(QStringLiteral(":/assets/images/image_net_book.jpg")); //设置ICON的图标

	//aIconNet.addFile(tr("D:\\图\\1a.jpg")); //设置ICON的图标
	QListWidgetItem* aItem; //每一行是一个QListWidgetItem
	aItem = new QListWidgetItem(); //新建一个项
	if (book.IsWeb())
	{
		aItem->setIcon(aIconNet);//设置图标
	}
	else
	{
		aItem->setIcon(aIcon);//设置图标
		QFileInfo info(book.path);
		book.strAuthor = tr("%1M").arg((float)(info.size() / 1000) / 1000);
		QDateTime dt = info.lastModified();
		book.strUpdateTime = tr("%1").arg(dt.toString("yyyy-MM-dd hh:mm:ss"));
	}
	//aItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled);
	QString strBookInfo(GetListWidgetBookItemString(book));
	aItem->setText(strBookInfo); //设置文字标签
	g_mtxListBookPosChange.lock();
	if (indexItem == 0)
	{
		ui->listWidgetBook->insertItem(0, aItem); //增加一个项
		m_listBookInfo.push_front(book);
	}
	else
	{
		ui->listWidgetBook->addItem(aItem);
		m_listBookInfo.push_back(book);
	}
	g_mtxListBookPosChange.unlock();
	ui->listWidgetBook->update();
}

void MainWindow::DelBook(QString strPath)
{
	size_t row = 0;
	for (; row < m_listBookInfo.size(); row++)
	{
		if (m_listBookInfo[row].path.size() == strPath.size() && m_listBookInfo[row].path == strPath)
		{
			break;
		}
	}
	DelBook(row);
}

void MainWindow::DelBook(size_t row)
{
	g_mtxListBookPosChange.lock();
	if (row >= m_listBookInfo.size()) return;
	m_listBookInfo.erase(m_listBookInfo.begin() + row);
	QListWidgetItem* item = ui->listWidgetBook->takeItem((int)row);
	delete item;
	ui->listWidgetBook->update();
	g_mtxListBookPosChange.unlock();
	SaveBookListInfo();
}

void MainWindow::ReadBookListInfo()
{
	m_listBookInfo.clear();
	QSettings set(tr(BOOK_LIST_SAVE_DIR"BooksListInfo.info"), QSettings::IniFormat);
	set.setIniCodec(QTextCodec::codecForName("UTF-8"));

	int i = 0;
	for (;; i++)
	{
		sBookInfo book;
		book.name = set.value(QString::number(i) + "/name").toString();
		if (book.name.isEmpty())
			return;
		book.path = set.value(QString::number(i) + "/path").toString();
		if (book.IsWeb())
		{
			book.strAuthor = set.value(QString::number(i) + "/author").toString();
			book.strUpdateTime = set.value(QString::number(i) + "/updatetime").toString();
			book.status = set.value(QString::number(i) + "/status").toString();
			book.utf8 = set.value(QString::number(i) + "/utf8").toBool();
		}
		else
		{
			QFileInfo info(book.path);
			if (info.size() == 0)
				continue;
			book.strAuthor = tr("%1M").arg((float)(info.size() / 1000) / 1000);
			QDateTime dt = info.lastModified();
			book.strUpdateTime = tr("%1").arg(dt.toString("yyyy-MM-dd hh:mm:ss"));
		}
		book.strChapterHead = set.value(QString::number(i) + "/chapter").toString();
		book.maxChapter = set.value(QString::number(i) + "/maxChapter", 100).toInt();
		book.sort = (Qt::CheckState)set.value(QString::number(i) + "/sort", Qt::CheckState::Unchecked).toInt();
		AddBookInfoToWeiget(book, -1);
	}
}

void MainWindow::on_btnClearBook_clicked()
{
	g_mtxListBookPosChange.lock();
	m_listBookInfo.clear();
	ui->listWidgetBook->clear();
	SaveBookListInfo();
	g_mtxListBookPosChange.unlock();
}

void MainWindow::on_btnAddBookAuto_clicked()
{
	//选择多个文件
	//获取应用程序的路径
	QString curPath = QDir::currentPath();//获取系统当前目录
#ifdef __ANDROID__
	curPath = ROOT_PATH;
#endif

	QStringList fileList;
	if (m_dlgAutoAddBook.exec() == QDialog::Accepted)   //如果成功的执行
	{
		fileList = m_dlgAutoAddBook.selectedFiles();      //返回文件列表的名称
	}
	else
		m_dlgAutoAddBook.close();

	int i = 0;
	for (; i < fileList.count(); i++)
	{
		QString strPath = fileList.at(i);
		QFileInfo  info = QFileInfo(fileList.at(i));
		AddBookInfoToWeiget(sBookInfo(info.fileName(), strPath), 0);
	}

	SaveBookListInfo();
}

void MainWindow::updateListWidgetBook()
{
	//设置当前读到的章更新到书架
	if (m_listBookInfo.size() != 0 && m_listBookInfo[0].chapter < m_dlgBookRead.m_chapterList.size())
	{
		auto& strChapterHead = m_dlgBookRead.m_chapterList[m_listBookInfo[0].chapter].head;
		if (!strChapterHead.isEmpty())
		{
			m_listBookInfo[0].strChapterHead = strChapterHead;
			QString strBookInfo(GetListWidgetBookItemString(m_listBookInfo[0]));

			sBookInfo& book = m_listBookInfo[0];
			if (book.IsWeb())
			{
				QIcon aIconNet;
				QString strFilePathImage = BOOK_LIST_SAVE_DIR"cache/" + book.name + WEB_BOOK_IMAGE_FILE_NAME;
				struct stat buffer;
				if (stat(strFilePathImage.toLocal8Bit(), &buffer) == 0)
					aIconNet.addFile(strFilePathImage);
				else
					aIconNet.addFile(QStringLiteral(":/assets/images/image_net_book.jpg")); //设置ICON的图标
				ui->listWidgetBook->item(0)->setIcon(aIconNet);
			}
			ui->listWidgetBook->item(0)->setText(strBookInfo);
			SaveBookListInfo();
		}
	}
}

void MainWindow::on_btnAbout_clicked()
{
	QString dlgTitle = tr("关于");
	static const string strVersion = COMLETE_VERSION;
	QString strInfo = QString::asprintf(
		"飞天阅读器\n"
		"版本:%s\n"
		"保留所有版权\n"
		"作者:心若冰清自然开心\n"
		"问题反馈邮箱:xs595@qq.com\n"
		"说明:\n"
		"1.安卓系统后台语音朗读，需要开启通知权限\n", strVersion.c_str());
	QMessageBox::about(this, dlgTitle, strInfo);
}

void MainWindow::on_btnBookCity_clicked()
{
#if WEB_TEST

	//webView.loadDataWithBaseURL(null, "<html><head><title> 欢迎您 </title></head>" +
	//	"<body><h2>使用webview显示 html代码</h2></body></html>", "text/html", "utf-8", null);

	QtWebView::initialize();
	QGuiApplication::setApplicationDisplayName("FreeReader");
	const QString initialUrl = QStringLiteral("https://www.biquge.biz");

	static QQmlApplicationEngine engine;
	QQmlContext* context = engine.rootContext();
	context->setContextProperty(QStringLiteral("utils"), new Utils(&engine));
	context->setContextProperty(QStringLiteral("initialUrl"),
		Utils::fromUserInput(initialUrl));
	QRect geometry = QGuiApplication::primaryScreen()->availableGeometry();
	//if (!QGuiApplication::styleHints()->showIsFullScreen()) {
	//	const QSize size = geometry.size() * 4 / 5;
	//	const QSize offset = (geometry.size() - size) / 2;
	//	const QPoint pos = geometry.topLeft() + QPoint(offset.width(), offset.height());
	//	geometry = QRect(pos, size);
	//}
	context->setContextProperty(QStringLiteral("initialX"), geometry.x());
	context->setContextProperty(QStringLiteral("initialY"), geometry.y());
	context->setContextProperty(QStringLiteral("initialWidth"), geometry.width());
	context->setContextProperty(QStringLiteral("initialHeight"), geometry.height());

	engine.load(QUrl(QStringLiteral("qrc:/assets/web.qml")));
	if (engine.rootObjects().isEmpty())
		return;
#else

#if WEB_WIDGET_ENABLE
	m_webWidget.show();
#else
	m_dlgBookCity.show();
#endif

#endif
}

void MainWindow::setGlobalFont()
{
	QString strFont = g_set->value("global/font_family", font().family()).toString();
	int size = g_set->value("global/font_size", TEXT_SIZE_DEFAULT).toInt();
	QFont font = this->font();
	font.setPointSize(size);
	font.setFamily(strFont);
	auto listWidget = findChildren<QWidget*>();
	for (auto& widget : listWidget)
	{
		widget->setFont(font);
	}

	int count = ui->listWidgetBook->count();
	for (int i = 0; i < count; i++)
	{
		auto item = ui->listWidgetBook->item(i);
		item->setFont(font);
	}

	QScreen* myScreen = QGuiApplication::primaryScreen();
	QRect rt = myScreen->availableVirtualGeometry();
	QMainWindow::setFont(font);
	qApp->setFont(font);

	size = fontMetrics().lineSpacing() * 2;
	int min = rt.height() / 8 < rt.width() / 6 ? rt.height() / 8 : rt.width() / 6;
	if (size > min)
		size = min;
	QSize qsize(size, size);
	auto listWidgetBtn = findChildren<QToolButton*>();
	for (auto& widget : listWidgetBtn)
	{
		widget->setFixedSize(qsize);
		widget->setIconSize(qsize);
	}

	setGeometry(rt);
	m_dlgBookRead.setGeometry(rt);
	m_dlgBookRead.setFixedSize(rt.size());
#if WEB_WIDGET_ENABLE
	m_webWidget.setGeometry(rt);
#endif
	m_dlgBookCity.setGeometry(rt);
	m_dlgAutoAddBook.setGeometry(rt);
	m_dlgBookRead.m_dlgContents.setGeometry(rt);
	m_dlgBookRead.m_dlgSearchString.setGeometry(rt);
	m_dlgSet.setGeometry(rt);
}

void MainWindow::on_btnSet_clicked()
{
	m_dlgSet.show();
}

void MainWindow::on_btnProcessExit_clicked()
{
	close();
}

void MainWindow::on_btnUpdateBook_clicked()
{
	static bool bStop = false;
	if (ui->btnUpdateBook->text().indexOf(BUTTON_IN_PROGRESS) == -1)
	{
		bStop = false;
		std::thread([&]
			{
				g_mtxListBookPosChange.lock();
				auto listBookInfo(m_listBookInfo);
				g_mtxListBookPosChange.unlock();
				QString strSrc = ui->btnUpdateBook->text();
				ui->btnUpdateBook->setText(strSrc + BUTTON_IN_PROGRESS);
				for (string::size_type j = 0; j < listBookInfo.size(); j++)
				{
					auto& book = listBookInfo[j];
					if (bStop)
						break;
					if (book.IsWeb() && -1 != book.status.indexOf("连载"))
					{
						vector<BookChapterList> chapterList;
						int iRet = ThreadCacheBook::GetChapterList(book, chapterList, true);
						if (iRet >= 0)
						{
							QString strBookInfo(GetListWidgetBookItemString(book));
							QIcon aIconNet;
							QString strFilePathImage = BOOK_LIST_SAVE_DIR"cache/" + book.name + WEB_BOOK_IMAGE_FILE_NAME;
							struct stat buffer;
							if (stat(strFilePathImage.toLocal8Bit(), &buffer) == 0)
								aIconNet.addFile(strFilePathImage);
							else
								aIconNet.addFile(QStringLiteral(":/assets/images/image_net_book.jpg")); //设置ICON的图标

							g_mtxListBookPosChange.lock();
							for (string::size_type i = 0; i < m_listBookInfo.size(); i++)
							{
								if (book.path == m_listBookInfo[i].path)
								{
									if (i == 0 && m_dlgBookRead.isVisible() &&
										m_dlgBookRead.m_chapterList.size() != chapterList.size())
									{
										m_dlgBookRead.m_chapterList = chapterList;
										m_dlgBookRead.m_dlgContents.ListWidgetClear();
										book.chapter = m_listBookInfo[0].chapter;
										book.pos = m_listBookInfo[0].pos;
									}

									m_listBookInfo[i] = book;
									auto item = ui->listWidgetBook->item((int)i);
									item->setIcon(aIconNet);
									item->setText(strBookInfo);
									item->setHidden(true);
									item->setHidden(false);
									break;
								}
							}
							g_mtxListBookPosChange.unlock();
						}
					}
				}
				SaveBookListInfo();
				ui->btnUpdateBook->setText(strSrc);
			}).detach();
	}
	else
		bStop = true;
}

void MainWindow::CallNativeOnPause()
{
	g_bAndroidForegroundRunning = false;
	LOG_DEBUG_P("tts->state():%d", m_dlgBookRead.m_speech->state());
}

void MainWindow::CallNativeOnResume()
{
	g_bAndroidForegroundRunning = true;
	LOG_DEBUG_P("tts->state():%d", m_dlgBookRead.m_speech->state());

	if (m_dlgBookRead.isVisible())
	{
		m_dlgBookRead.MoveCursorToLine();
	}
}
